package com.zhg.shortlink.domain.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;

import java.time.LocalDateTime;

import static com.zhg.shortlink.constant.CommonConstants.SHORT_CODE_LENGTH;

/**
 * @author 朱洪刚
 * @version 1.0
 * @data 2025/10/20 11:48
 */
@Data
@TableName("short_url_mapping")
public class ShortUrlMapping {

    @NotBlank(message = "短链编码不能为空")
    @Size(max = SHORT_CODE_LENGTH, message = "短链编码长度不能超过" + SHORT_CODE_LENGTH)
    @TableId(value = "short_code")
    private String shortCode;

    @NotBlank(message = "原始URL不能为空")
    @Size(max = 2048, message = "原始URL长度不能超过2048")
    @TableField(value = "origin_url")
    private String originUrl;

    @NotBlank(message = "原始URL哈希值不能为空")
    @TableField(value = "origin_url_hash")
    private String originUrlHash;

    @TableField(value = "create_time")
    private LocalDateTime createTime;

    @TableField(value = "update_time")
    private LocalDateTime updateTime;


    @TableField(value = "expire_days")
    private Integer expireDays = 7;


    @TableField(value = "access_count")
    private Long accessCount = 0L;


    @TableField(value = "status")
    private Integer status = 1; // 1:正常 0:禁用


    @Size(max = 30, message = "创建人长度不能超过30字符")
    private String creator;

    /**
     * 是否过期
     *
     * @return 是否过期
     */
    public boolean isExpired() {
        // 如果过期天数为null或小于等于0，表示永不过期
        if (expireDays == null || expireDays <= 0) {
            return false;
        }

        // 如果创建时间为null，认为已过期（异常情况）
        if (createTime == null) {
            return true;
        }

        // 计算过期时间：创建时间 + 过期天数
        LocalDateTime expireTime = createTime.plusDays(expireDays);

        // 判断当前时间是否超过过期时间
        return LocalDateTime.now().isAfter(expireTime);
    }

}
